import { Models } from "../common/typings/model"
import HttpErrors from "../core/HttpException"
import dbConfig from '../config/dbConfig'
import logger from './logs'
const catchError = async (ctx: Models.Ctx,next: Function)=> {
    try {

        await next()

        logger.info(ctx.method,ctx.originalUrl,`query:${JSON.stringify(ctx.query || '')}`,`body:${JSON.stringify(ctx.body || '')}`)
    }
    catch (error) {
        // 需要返回的信息
        // HTTP Status Code 
        // message
        // error_code 详细错误，开发者自己定义
        // 错误类型：已知错误、未知错误
        let isHttpException = error instanceof HttpErrors.HttpException
        let isDev = dbConfig.environment === 'dev'

        if(isDev && !isHttpException) {//已知异常
            if(dbConfig.environment === 'dev') {
                throw error
            }
            
        }
        else if(!isDev && !isHttpException) {
            ctx.body = {
                msg:'未知错误',
                errorCode: 9999,
                requestUrl: `${ctx.method} ${ctx.path}`
            }
            ctx.status = 500
        }
        if(isHttpException) {
            ctx.body = {
                msg: error.message,
                errorCode: error.errorCode,
                requestUrl: `${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code
        }
        logger.error(ctx.method,ctx.originalUrl,`query:${JSON.stringify(ctx.query || '')}`,`body:${JSON.stringify(ctx.body || '')}`)
    }
    // console.log(ctx)
    // logger.info(ctx.method,ctx.originalUrl,`query:${JSON.stringify(ctx.query || '')}`,`body:${JSON.stringify(ctx.body || '')}`)
}
export {
    catchError
}
